<?php


namespace app\app\controller;


use app\common\controller\Homebase;
use EasyWeChat\Factory;
use think\console\Input;
use think\console\Output;
use think\Db;
use think\Validate;
use think\facade\Cache;
use think\facade\Request;

use think\Image;

define("SECRETID", "3d14e939ae6c21d046418411f91c2074");
/** 产品私有密钥，服务端生成签名信息使用，请严格保管，避免泄露 */
define("SECRETKEY", "228d1b953a5a83a415fc99a76a2bb2e7");
/** 业务ID，易盾根据产品业务特点分配 */
define("BUSINESSID", "ae8f96f97441ec9888100686429bb823");
/** 易盾反垃圾云服务文本在线检测接口地址 */
define("API_URL", "http://as.dun.163.com/v3/text/check");
/** api version */
define("VERSION", "v3.1");
/** API timeout*/
define("API_TIMEOUT", 2);

/** 业务ID，易盾根据产品业务特点分配 */
define("BUSINESSID_IMG", "56683f4b935888e1ccb9531c85449772");
/** 易盾反垃圾云服务文本在线检测接口地址 */
define("API_URL_IMG", "http://as.dun.163.com/v4/image/check");
/** api version */
define("VERSION_IMG", "v4");
/** API timeout*/
define("API_TIMEOUT_IMG", 10);

require("util.php");

class Index extends Homebase
{
    //-------------------------------------网易云配置-------------------------------
    public function check($params)
    {
        $params["secretId"] = SECRETID;
        $params["businessId"] = BUSINESSID;
        $params["version"] = VERSION;
        $params["timestamp"] = time() * 1000;// time in milliseconds
        $params["nonce"] = sprintf("%d", rand()); // random int

        $params["signatureMethod"] = SIGNATURE_METHOD;
        $params = toUtf8($params);
        $params["signature"] = gen_signature(SECRETKEY, $params);
        // var_dump($params);

        $result = curl_post($params, API_URL, API_TIMEOUT);
        if ($result === FALSE) {
            return array("code" => 500, "msg" => "file_get_contents failed.");
        } else {
            return json_decode($result, true);
        }
    }

    public function check2()
    {
        $content = $this->request->param("content");
        // $content="我感觉商家做的很好吃的呢，很不错 棒棒的";
        $params = array(
            "dataId" => "ebfcad1c-dba1-490c-b4de-e784c2691768",
            "content" => $content
            // "dataType"=>"1",
            // "ip"=>"123.115.77.137",
            // "account"=>"php@163.com",
            // "deviceType"=>"4",
            // "deviceId"=>"92B1E5AA-4C3D-4565-A8C2-86E297055088",
            // "callback"=>"ebfcad1c-dba1-490c-b4de-e784c2691768",
            // "publishTime"=>round(microtime(true)*1000)
        );

        $ret = $this->check($params);
        // var_dump($ret);
        if ($ret["code"] == 200) {
            $action = $ret["result"]["action"];
            $taskId = $ret["result"]["taskId"];
            $labelArray = $ret["result"]["labels"];
            if ($action == 0) {
                msg(0, 'taskId=' . $taskId . '文本机器检测结果：通过\n', $ret);
//                echo "taskId={$taskId}，文本机器检测结果：通过\n";
            } else if ($action == 1) {
                msg(-1, "taskId={$taskId}，文本机器检测结果：嫌疑，需人工复审，分类信息如下", $labelArray);
                //echo "taskId={$taskId}，文本机器检测结果：嫌疑，需人工复审，分类信息如下：".json_encode($labelArray)."\n";
            } else if ($action == 2) {
                msg(-1, "taskId={$taskId}，文本机器检测结果：不通过，分类信息如下：", $labelArray);
                // echo "taskId={$taskId}，文本机器检测结果：不通过，分类信息如下：".json_encode($labelArray)."\n";
            }
        } else {
            msg(-1, $ret, '');
//            var_dump($ret); // error handler
        }
    }


    public function check_img($params)
    {
        $params["secretId"] = SECRETID;
        $params["businessId"] = BUSINESSID_IMG;
        $params["version"] = VERSION_IMG;
        $params["timestamp"] = time() * 1000;// time in milliseconds
        $params["nonce"] = sprintf("%d", rand()); // random int

        $params["signatureMethod"] = SIGNATURE_METHOD;
        $params = toUtf8($params);
        $params["signature"] = gen_signature(SECRETKEY, $params);
        // var_dump($params);

        $result = curl_post($params, API_URL_IMG, API_TIMEOUT_IMG);
        // var_dump($result);
        if ($result === FALSE) {
            return array("code" => 500, "msg" => "file_get_contents failed.");
        } else {
            return json_decode($result, true);
        }
    }

    public function check_img2()
    {
        $img_url = $this->request->param("img_url");
        $images = array();
        array_push($images, array(// type=1表示传图片url检查
            "name" => $img_url,
            "type" => 1,
            "data" => $img_url,
        ));
//        foreach ($img_url as $k=>$v){
//            array_push($images, array(// type=1表示传图片url检查
//                "name" => $v,
//                "type" => 1,
//                "data" => $v,
//            ));
//        }
        $params = array(
            "images" => json_encode($images)
            // "account"=>"php@163.com",
            // "ip"=>"123.115.77.137",
        );

        $ret = $this->check_img($params);

        if ($ret["code"] == 200) {
            $antispamArray = $ret["antispam"];

            foreach ($antispamArray as $index => $image_ret) {
                $name = $image_ret["name"];
                $taskId = $image_ret["taskId"];
                $status = $image_ret["status"];
                if ($status == 0) {
                    $action = $image_ret["action"];
                    $labelArray = $image_ret["labels"];

                    // echo "taskId={$taskId}，name={$name}，action={$action}\n";
                    foreach ($labelArray as $index => $label) {
                        // subLabels为二级分类数组，根据需要解析
                        $subLabels = $label["subLabels"];
                        // echo "label:{$label["label"]}, level={$label["level"]}, rate={$label["rate"]}\n";
                    }
                    if ($action == 0) {
                        msg(0, '图片机器检测结果：最高等级为：正常', $image_ret);

                    } else if ($action == 1) {
                        msg(-1, '图片机器检测结果：最高等级为：嫌疑', $image_ret);
                    } else if ($action == 2) {
                        msg(-2, '图片机器检测结果：最高等级为：嫌疑', $image_ret);
                    }
                } else {
                    msg(-1, "图片检测失败,taskId:{$taskId}, status={$status}, name={$name}", $ret);
                    // status对应失败状态码：610：图片下载失败，620：图片格式错误，630：其它
                    echo "图片检测失败,taskId:{$taskId}, status={$status}, name={$name}\n";
                }
            }
            //暂时不用
            // 图片OCR结果
//            $ocrArray = $ret["ocr"];
//            foreach ($ocrArray as $index => $ocr) {
//                $name = $ocr["name"];
//                $taskId = $ocr["taskId"];
//                $detailArray = $ocr["details"];
//                echo "taskId={$taskId}，name={$name}\n";
//                // 产品需根据自身需求，自行解析处理，本示例只是简单输出ocr结果信息
//                foreach ($detailArray as $index => $detail) {
//                    // 识别ocr文本内容
//                    $content = $detail["content"];
//                    // ocr片段及坐标信息
//                    $lineContents = $detail["lineContents"];
//                }
//            }
//            // 图片人脸检测结果
//            $faceArray = $ret["face"];
//            foreach ($faceArray as $index => $face) {
//                $name = $face["name"];
//                $taskId = $face["taskId"];
//                $detailArray = $face["details"];
//                echo "taskId={$taskId}，name={$name}\n";
//                // 产品需根据自身需求，自行解析处理，本示例只是简单输出人脸结果信息
//                foreach ($detailArray as $index => $detail) {
//                    // 识别人脸数量
//                    $faceNumber = $detail["faceNumber"];
//                    // 人物信息及坐标信息
//                    $faceContents = $detail["faceContents"];
//                }
//            }
//            // 图片质量检测结果
//            $qualityArray = $ret["quality"];
//            foreach ($qualityArray as $index => $quality) {
//                $name = $quality["name"];
//                $taskId = $quality["taskId"];
//                $detailArray = $quality["details"];
//                echo "taskId={$taskId}，name={$name}\n";
//                // 产品需根据自身需求，自行解析处理，本示例只是简单输出质量结果信息
//                foreach ($detailArray as $index => $detail) {
//                    // 图片美观度分数
//                    $aestheticsRate = $detail["aestheticsRate"];
//                    // 图片基本信息
//                    $metaInfo = $detail["metaInfo"];
//                    // 图片边框信息
//                    $boarderInfo = $detail["boarderInfo"];
//                }
//            }
        } else {
            msg(-1, "请求错误，请检查参数网络", $ret);
//            var_dump($ret);
        }

    }

    //-----------------------------------百度云配置---------------------------------
    public function run()
    {
        $appId = config('wechat.baidu.appId');
        $api_key = config('wechat.baidu.api_key');
        $secret_key = config('wechat.baidu.secret_key');
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://aip.baidubce.com/oauth/2.0/token?client_id={$api_key}&client_secret={$secret_key}&grant_type=client_credentials",
            CURLOPT_TIMEOUT => 30,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_HTTPHEADER => array(
                'Content-Type: application/json',
                'Accept: application/json'
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        return $response;
    }

    public function getBaiduToken()
    {
        $baidu_token = Cache::get('baidu_token');
        if ($baidu_token) {
            return $baidu_token;
        } else {
            $ret = $this->run();
            $ret = json_decode($ret, true);
            if (isset($ret['access_token'])) {
                Cache::set('baidu_token', $ret['access_token'], 2591000);
                return $ret['access_token'];
            } else {
                msg(-1, 'token授权失败,请查看原因', $ret);
            }
        }
    }

    //文本审核
    public function textVerity()
    {
        $data = $this->request->param();
        $token = $this->getBaiduToken();
        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token=' . $token;
        $bodys = array(
            'text' => $data['content']
        );
        try {
            $res = request_post($url, $bodys);
            $res = json_decode($res, true);
            msg($res['conclusionType'], $res['conclusion'], $res);
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), '');
        }
    }

    //img 图片审核 百度审核
    public function imgVerity()
    {
        $data = $this->request->param();
        $token = $this->getBaiduToken();
        $url = 'https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=' . $token;
        $bodys = array(
            'imgUrl' => $data['img_url']
        );
        try {
            $res = request_post($url, $bodys);
            $res = json_decode($res, true);
            msg($res['conclusionType'], $res['conclusion'], $res);
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), '');
        }
    }


    /**
     * 请求
     * @param $url
     * @param null $data
     * @return bool|string
     */
    private function http_request($url, $data = null)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, TRUE);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json'
            ));
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
        exit();

    }

    /**
     * 获取openid
     */
    public function wxLogin()
    {
        $code = $this->request->param("code");
        $appId = config('wechat.appID');
        $secret = config('wechat.AppSecret');
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appId . '&secret=' . $secret . '&js_code=' . $code . '&grant_type=authorization_code';
        $res = lmcurl($url);
        msg(0, "成功", $res);
    }

    /**
     * 上传图片
     */
    // todo 转换成webp 看图片压缩
    public function upload_img()
    {
        $files = $this->request->file('file');//获取图片
        $info = $files->move(ROOT_PATH . 'public' . '/' . 'uploads');

        if ($info) {

            $logo = '/' . 'uploads' . '/' . $info->getSaveName();

            $datas = $info->getInfo();

            $img['path'] = $logo;

            $img['mime'] = $datas['type'];

            $img['name'] = $datas['name'];

            $img['size'] = $datas['size'];

            $img['sha1'] = $info->hash('sha1');

            $img['md5'] = $info->hash('md5');

            $img['driver'] = 'local';

            $img['create_time'] = time();

            $img['update_time'] = time();

            $img['status'] = 1;

            $img['ext'] = $info->getExtension();

            $id = Db::name('attachment')->insertGetId($img);
            //todo 关闭oss
//            if (config('is_oss') == 1) {
//                upload_local_file($id);
//            }
            $d = db('attachment')->where('id', $id)->find();
            if ($d['type'] == 1) {
                $d['path'] = conf("wechat", "url") . str_replace('\\', '/', $d['path']);
            } else {
                $d['path'] = conf("wechat", "url") . $d['path'];
            }
            msg(0, "获取成功", $d);

        } else {
            echo $files->getError();
        }
        //msg(0, "成功", $url);
    }

    /**
     * 获取手机号
     */
    public function GetPhone()
    {
        $code = $this->request->param("code");
        $tmp = getAccessToken();
        $tmptoken = json_decode($tmp);
        $token = $tmptoken->access_token;
        $data['code'] = $code;//前端获取code

        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";

        $info = $this->http_request($url, json_encode($data), 'json');

        // 一定要注意转json，否则汇报47001错误
        $tmpinfo = json_decode($info);
        $code = $tmpinfo->errcode;
        $phone_info = $tmpinfo->phone_info;
        //手机号
        $phoneNumber = $phone_info->phoneNumber;
        if ($code == '0') {
            msg(0, "成功", $phoneNumber);

        } else {
            msg(-1, "失败", $phoneNumber);
        }
    }

    /**
     * @return void 保存用户信息
     */
    public function deuser()
    {
        $data = $this->request->param();

        $datas['openid'] = $data['openid'];

        $datas['reg_ip'] = $this->request->ip();

        $datas['mobile'] = $data['mobile'];

        $datas['nickname'] = $data['nickname'];

        $datas['avatarUrl'] = $data['avatarUrl'];

        if (isset($data['invite_id'])) {
            $datas['invite_id'] = $data['invite_id'];
        }

        $rules = [
            'openid' => 'require',
            'mobile' => 'require',
//            'nickname' => 'require',
//            'avatarUrl' => 'require',
        ];
        $message = [
            'openid.require' => 'openid必须',
            'mobile.require' => '手机必须',
//            'nickname.require' => '昵称必须',
//            'avatarUrl.require' => '头像必须',
        ];
        $validate = new Validate($rules, $message);
        $result = $validate->check($data);
        if (!$result) {
            msg(-1, '缺少信息', '');
        }
        $stmt = Db::name('member')->where('openid', $datas['openid'])->find();
        if ($stmt) {
            $datas['last_login_time'] = time();
            unset($datas['nickname']);
            unset($datas['avatarUrl']);
            Db::name('member')->where('openid', $datas['openid'])->update($datas);
            $member = Db::name('member')->where('openid', $datas['openid'])->find();
            if ($member['status'] == 0) {
                responseJson(-200, '用户已冻结', $member);
            }
            msg(0, '查询成功', $member);
        } else {
            $datas['create_time'] = time();
            $datas['status'] = 1;
            //一键默认登录 设置默认昵称 默认头像
            $datas['nickname'] = '用户' . rand(0000, 9999);
            $datas['avatarUrl'] = config('site.web_default_avatar');
            $user_id = Db::name('member')->insertGetId($datas);
            if (isset($data['invite_id'])) {
                $coupon_info = Db::name('coupons')->where([
                    'cate_id' => 4,
                    'is_del' => 0,
                    'status' => 1
                ])->find();
                getCoupons($data['invite_id'], $coupon_info, 3, $user_id);
            }
            msg(0, '新建成功', $datas);
        }
    }

    /**
     * 获取各项配置
     */
    public function getConfigAdmin()
    {
        $data = $this->request->param();
        if ($data['set_name'] && isset($data['set_name'])) {
            msg(0, '查询完成', config('site.' . $data['set_name']));
        }
        msg(-1, '请输入查询内容', '');
    }

    /**
     * 获取banner图
     */
    public function getBanner()
    {
        $data = Db::name('banner')->where(['status' => 1, 'is_del' => 0])->order('sort desc')->select();
        msg(0, '查询成功', $data);
    }

    //通过坐标获取位置信息
    public function getAddressByLocation()
    {
        $data = $this->request->param();
        //当前维度 经度 搜索关键字 页数 所在市
        $data_list = getAddressByLocation2($data['latitude'], $data['longitude']);
        $data_list = json_decode($data_list, true);
        if ($data_list['code'] == 0) {
            $data_list['data']['location']['lat'] = $data['latitude'];
            $data_list['data']['location']['lng'] = $data['longitude'];
            msg(0, '查询成功', $data_list['data']);
        } else {
            msg(-1, $data_list['data'], '');
        }
    }

    //通过市获取坐标
    public function getCityLocation()
    {
        $data = $this->request->param();
        //当前维度 经度 搜索关键字 页数 所在市
        $data_list = getLWByAddress($data['city']);
        $data_list = json_decode($data_list, true);
        if ($data_list['code'] == 0) {
            msg(0, '查询成功', $data_list['data']);
        } else {
            msg(-1, $data_list['data'], '');
        }
    }

    //获取评价标签
    public function getCommentLabList()
    {
        $result = Db::name('comment_label')
            ->where([
                'status' => 1,
                'is_del' => 0,
            ])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $result);
    }

    public function getWeatherByCity()
    {
        $address = getCityByIP();
        $data = getWeatherByCity($address['city']);
        msg(0, '查询成功', $data);
    }


    //定时任务
    // 发送消息
    public function tableSendMsg()
    {
        $data_list = Db::name('platform_msg')->where([
            'is_del' => 0,
            'is_send' => 0
        ])->select();
        foreach ($data_list as $k => $v) {

        }
    }

    // 订单定时
    public function orderTime()
    {
        $step = 6;
        for ($i = 0; $i < 60; $i += $step) {
            $order_list = Db::name('order')->where([
                'is_del' => 0,
                'status' => 1
            ])->select();
            foreach ($order_list as $k => $v) {
                //超过15分钟未支付为失效
                $a = time() - ($v['create_time'] + 15 * 60);
                if ($a >= 0) {
                    $update = array(
                        'id' => $v['id'],
                        //todo 已取消
                        'status' => 7,
                        'tui_reason' => '定时取消' . date('Y-m-d H:i:s', time()),
                    );
                    Db::name('order')->update($update);
                }
            }
            file_put_contents('d.txt', date('Y-m-d H:i:s', time()));
            sleep($step);
        }
    }

    // 订单支付完成失效
    public function orderTime2()
    {
        $order_list = Db::name('order')->where([
            'is_del' => 0,
            'status' => 2
        ])->select();
        //失效时间为当天24时
        $now_day = date('Y-m-d', time());
        foreach ($order_list as $k => $v) {
            if (date('Y-m-d', $v['pay_time']) < $now_day) {
                //订单失效
                $update = array(
                    'id' => $v['id'],
                    //todo 已失效
                    'status' => 5,
                    'tui_reason' => '订单已超时，定义失效' . date('Y-m-d H:i:s', time()),
                );
                Db::name('order')->update($update);
            }
        }
        msg(0, '订单失效已完成', date('Y-m-d H;i:s', time()));
    }

    //食品袋定时任务
    public function goodsTime()
    {
        //设置时间 不是本天的设置库存为0 并设置下架
        $goods_list = Db::name('goods')->where([['status', 'in', [1, 4]], ['is_del', '=', 0]])->select();
        foreach ($goods_list as $k => $v) {
            //设置的时间是不是今天的
            if (!isToday($v['set_time'])) {
                $goods_update = array(
                    'id' => $v['id'],
                    'status' => 4,
                    'inventory' => 0
                );
                Db::name('goods')->update($goods_update);
                if ($v['is_ming']) {
                    $yesterdayTimestamp = strtotime("yesterday");
                    $isYesterday = ($v['set_time'] > $yesterdayTimestamp) && ($v['set_time'] < $yesterdayTimestamp + 86400);
                    if ($isYesterday) {
                        $goods_update2 = array(
                            'id' => $v['id'],
                            'inventory' => $v['inventory_ming'],
                            'is_ming' => 0,
                            'inventory_ming' => 0,
                            'qu_time_start' => $v['qu_time_start_ming'],
                            'qu_time_end' => $v['qu_time_end_ming'],
                            'purchase_time_start' => $v['purchase_time_start_ming'],
                            'purchase_time_end' => $v['purchase_time_end_ming'],
                            'set_time' => time(),
                            'qu_time_start_ming' => '',
                            'qu_time_end_ming' => '',
                            'purchase_time_start_ming' => '',
                            'purchase_time_end_ming' => '',
                            'status' => 1,
                        );
                        Db::name('goods')->update($goods_update2);
                    }
                }
            }

        }
        //判断时间是否是昨天的
    }

    //签到消息提醒
    public function signMsgTime()
    {

        $remind_time = config('site.qiandao_remind') ? config('site.qiandao_remind') : '2024-10-26 08:30:00';
        $remind_time = strtotime($remind_time);
        $remind_time = date('H:i:s', $remind_time);

        $now_day = date('Y-m-d', time());
        $now_time = date('H:i:s', time());


        $signMsgTime = Cache::get('signMsgTime');
        if (!$signMsgTime) {
            Cache::set('signMsgTime', $now_day, 86400);
        }
        if ($signMsgTime != $now_day) {
            if ($now_time >= $remind_time) {
                $member_list = Db::name('member')
                    ->where('openid', '<>', null)
                    ->select();
                foreach ($member_list as $k => $v) {
                    sendMessage($v['id'], '签到提醒', 2, 3, 0);
                }
                Cache::set('signMsgTime', $now_day, 86400);
                msg(1, '发送完成', date('Y-m-d H;i:s', time()));
            }
        } else {
            msg(0, '消息已发送', date('Y-m-d H;i:s', time()));
        }

    }

    //优惠券定时提醒
    public function couponsTime()
    {
        //过期24小时进行提醒
        $coupon_expire = config('site.coupon_expire') ? config('site.coupon_expire') : 24;
        //获取优惠券列表
        $member_coupons = Db::name('member_coupons')->where([
            ['is_del', '=', 0],
            ['status', '=', 1]
        ])->select();
        foreach ($member_coupons as $k => $v) {
            $c = $v['end_time'] - time();
            if ($c < 3600 * $coupon_expire) {
                sendMessage($v['member_id'], '优惠券到期提醒' . $member_coupons['name'], 3, 3, 0);
            }
            if (time() > $v['end_time']) {
                Db::startTrans();
                try {
                    $update = array(
                        'id' => $v['id'],
                        'status' => 4,
                    );
                    Db::name('member_coupons')->update($update);
                    Db::commit();
                    msg(0, '查询成功', '');
                } catch (\Exception $e) {
                    Db::rollback();
                    msg(-1, $e->getMessage(), '');
                }
            }
        }
    }

    //订单定时默认好评
    public function orderCommentime()
    {
        $mo_good_day = config('site.mo_good_day');
//        if($mo_good_day==''||$mo_good_day=null){
//            $mo_good_day==5;
//        }
        $order_list = Db::name('order')
            ->where([
                ['is_del', '=', 0],
                ['status', '=', 3],
                ['write_time', '<=', time() - 86400 * $mo_good_day]
            ])->select();
        //5天不评价 默认 匿名好评
        Db::startTrans();
        try {
            foreach ($order_list as $k => $v) {
                $insert_data = array(
                    'member_id' => $v['member_id'],
                    'order_id' => $v['id'],
                    'goods_id' => $v['goods_id'],
                    'business_id' => $v['business_id'],
                    'content' => '默认好评',
                    'reply_id' => 0,
                    'score' => 5,
                    'anonymous' => 1,
                    'create_time' => time(),
                );
                $comment_id = Db::name('comment')->insertGetId($insert_data);
                //更新订单信息
                Db::name('order')->update(
                    [
                        'id' => $insert_data['order_id'],
                        'status' => 6,
                        'evaluate' => $insert_data['score']
                    ]
                );
                //更新商品评分
                updateGoodsEvaluate($v['goods_id']);
                //更新商家评分
                updateBusinessEvaluate($v['business_id']);
            }
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //发送消息定时
    public function sendPlatformMsg()
    {
        $data_list = Db::name('platform_msg')
            ->where([
                'is_click' => 0,
            ])
            ->select();
        foreach ($data_list as $k => $v) {
            $member_list = Db::name('member')
                ->where('openid', '<>', null)
                ->select();
            if ($v['is_time']) {
                //定时发送
                if (time() > $v['send_time']) {
                    foreach ($member_list as $k1 => $v1) {
                        sendMessage($v1['id'], $v['content'], $v['msg_cate_id'], 3, 0);
                    }
                    Db::name('platform_msg')->update([
                        'id' => $v['id'],
                        'is_click' => 1,
                        'is_send' => 1
                    ]);
                }
            } else {
                foreach ($member_list as $k1 => $v1) {
                    sendMessage($v1['id'], $v['content'], $v['msg_cate_id'], 3, 0);
                }
                Db::name('platform_msg')->update([
                    'id' => $v['id'],
                    'is_click' => 1
                ]);
            }
        }
        msg(0, '发送完成', date('Y-m-d H:i:s', time()));
    }

    //用户数量
    public function getUserNum()
    {
        $usernum = Db::name('member')->where('openid', '<>', null)->count();
        $usernum = str_pad($usernum, 8, '0', STR_PAD_LEFT);
        $usernum = (string)$usernum;
        $usernum = str_split($usernum);
        msg(0, '查询成功', $usernum);
    }

    //各个分类商品数量
    public function getCateGoods()
    {
        $cate_list = Db::name('operate_cate')
            ->where('is_del', '=', 0)
            ->where('status', '=', 1)
            ->order('sort desc')
            ->select();
        foreach ($cate_list as $k => $v) {
            $cate_list[$k]['goods_num'] = Db::name('goods')->where(
                [
                    ['status', 'in', [1, 4]],
                    ['is_del', '=', 0],
                    ['cate_id', 'like', '%' . $v['id'] . '%']
                ]
            )->count();
        }
        msg(0, '查询成功', $cate_list);
    }

    //
    public function getCenterNum()
    {
        //获取本月的时间戳
        $timestamp = getMonthTimestampRange(date('Y'), date('m'));
        $order_num = Db::name('order')->where([
            ['status', 'in', [2, 3, 5, 6]],
            ['pay_time', 'between', [$timestamp[0], $timestamp[1]]],
            ['is_del', '=', 0]
        ])->count();
        $business_num = Db::name('business') ->where('is_del','=',0)->where([
            ['status', 'in', [1, 2]],
            ['create_time', 'between', [$timestamp[0], $timestamp[1]]]
        ])->count();
        //本月营业额
        $platform_income = Db::name('order')->where([
            ['status', 'in', [2, 3, 5, 6]],
            ['pay_time', 'between', [$timestamp[0], $timestamp[1]]],
            ['is_del', '=', 0]
        ])->sum('pay_money');
        //
        $carbon_num = Db::name('order')->where([
            ['status', 'in', [2, 3, 5, 6]],
            ['pay_time', 'between', [$timestamp[0], $timestamp[1]]],
            ['is_del', '=', 0]
        ])->sum('carbon_emissions');;
        $data['order_num'] = $order_num;
        $data['business_num'] = $business_num;
        $data['platform_income'] = $platform_income;
        $data['carbon_num'] = $carbon_num;
        msg(0, '查询成功', $data);
    }
//订单状态 1待支付 2待取货 待核销 3待评价 4已退款 5已失效 6已评价 已核销 7已取消'
    //商家销售排行
    public function businessSellList()
    {
        $order_where[] = ['o.status', 'in', [2, 3, 5, 6]];
        $order_where[] = ['o.is_del', '=', 0];
        $data_lsit = Db::name('order')
            ->alias('o')
            ->join('business b', 'b.id=o.business_id')
            ->group('o.business_id')
            ->where($order_where)
            ->field('b.business_name,count(*) as order_num')
            ->limit(5)
            ->order('order_num desc')
            ->select();
        foreach ($data_lsit as $k => $v) {
            $data_lsit[$k]['top'] = $k + 1;
        }
        msg(0, '查询成功', $data_lsit);
    }

    //商品分类销售排行
    public function businessCateList()
    {
        $operate_cate_where[] = ['is_del', '=', 0];
        $operate_cate_where[] = ['status', '=', 1];

        $order_where[] = ['o.status', 'in', [2, 3, 5, 6]];
        $order_where[] = ['o.is_del', '=', 0];

        $cate_list = Db::name('operate_cate')
            ->where($operate_cate_where)
            ->select();
        foreach ($cate_list as $k => $v) {
            $orderList = Db::name('goods')
                ->alias('g')
                ->join('order o', 'g.id=o.goods_id')
                ->where($order_where)
                ->where([
                    ['g.cate_id', 'like', '%' . $v['id'] . '%']
                ])->count();
            $cate_list[$k]['order_num'] = $orderList;
        }
        usort($cate_list, function ($a, $b) {
            return $b['order_num'] - $a['order_num'];
        });
        foreach ($cate_list as $k => $v) {
            $cate_list[$k]['top'] = $k + 1;
            if ($k >= 5) {
                unset($cate_list[$k]);
            }
        }
        msg(0, '查询成功', $cate_list);
    }

    //用户购买排行
    public function memberOrderList()
    {
        $order_where[] = ['o.status', 'in', [2, 3, 5, 6]];
        $order_where[] = ['o.is_del', '=', 0];
        $member_list = Db::name('member')->order('order_num desc')->limit(9)->select();
        //订单不核销就算
        $member_list2 = Db::name('member')
            ->alias('m')
            ->join('order o', 'm.id=o.member_id')
            ->where($order_where)
            ->field('m.*,count(*) as order_num')
            ->group('o.member_id')
            ->order('order_num desc')->limit(9)->select();
        msg(0, '查询成功', $member_list2);
    }

    //会员新增走势
    public function memberAddTrend()
    {
        $member_where[] = ['openid', '<>', ''];
        for ($i = 7; $i >= 1; $i--) {
            $daysAgo[] = date('m.d', strtotime(-$i . " days"));
            $timescope = getTimestamp(-$i);
            $where[] = ['create_time', 'between', [$timescope[0], $timescope[1]]];
            $price[] = Db::name('member')
                ->where($where)
                ->where($member_where)
                ->count();
        }
        $data['date'] = $daysAgo;
        $data['num'] = $price;
        msg(0, '', $data);
    }

    //成交总额预览
    public function totalAmount()
    {
        for ($i = 5, $j = 0; $i >= 1; $i--, $j++) {
            $daysAgo[$j] = date('m.d', strtotime(-$i . " days"));
            $timescope = getTimestamp(-$i);
            //订单成交额 包括完成 和失效订单
            $Amount[$j] = Db::name('order')
                ->where([
                    ['status', 'in', [2, 3, 5, 6]],
                    ['pay_time', 'between', [$timescope[0], $timescope[1]]]
                ])->sum('pay_money');

            //同比
            if ($j == 0) {
                $tongBi[$j] = 1;
            } else {
                if ($Amount[$j - 1] > 0) {
                    $tongBi[$j] = $Amount[$j] / $Amount[$j - 1] * 100;
                    if ($tongBi[$j] < 0) {
                        $tongBi[$j] = 0;
                    }
                } else {
                    $tongBi[$j] = 0;
                }
            }
            //环比
            if ($j == 0) {
                $huanBi[$j] = 1;
            } else {
                if ($Amount[$j - 1] > 0) {
                    $huanBi[$j] = ($Amount[$j] - $Amount[$j - 1]) / $Amount[$j - 1] * 100;
                    if ($huanBi[$j] < 0) {
                        $huanBi[$j] = 0;
                    }
                } else {
                    $huanBi[$j] = 0;
                }
            }
        }
        $return[] = ['成交额', '同比', '环比'];
        for ($j = 1; $j <= 4; $j++) {
            $return[] = [$daysAgo[$j], $Amount[$j], $tongBi[$j], $huanBi[$j]];
        }
        $data['date'] = $daysAgo;
        $data['num'] = $Amount;
        $data['tongBi'] = $tongBi;
        $data['huanBi'] = $huanBi;
        msg(0, '', $return);
    }

    //商家入驻数据
    public function businessSettled()
    {
        //
        $data = array();
        $count = array();
        $business_status = array(
            ['id' => 0, 'name' => '待审核'],
            ['id' => 1, 'name' => '已入驻'],
            ['id' => 3, 'name' => '已拒绝'],
        );
        foreach ($business_status as $k => $v) {
            $business_num = Db::name('business') ->where('is_del','=',0)->where('status', '=', $v['id'])->count();
            $data[] = ['value' => $business_num, 'name' => $v['name']];
            $count[$v['name']] = $business_num;
        }
        msg(0, '', $data, $count);
    }

    //新客户注册超过7天 成交客户数据统计1
    public function dealRadio()
    {
        //获取新客户id
        $member_where[] = ['openid', '<>', ''];
        $order_where[] = ['status', 'in', [2, 3, 5, 6]];
        $order_where[] = ['is_del', '=', 0];
        //新用户 id
        $new_member = Db::name('member')
            ->where($member_where)
            ->where('create_time', '>', time() - (7 * 86400))
            ->column('id');
        //老用户
        $veteran_member = Db::name('member')
            ->where($member_where)
            ->where('create_time', '<', time() - (7 * 86400))
            ->column('id');
        //新客户成交额度
        $new_member_order = Db::name('order')
            ->where($order_where)
            ->where('member_id', 'in', $new_member)
            ->sum('pay_money');
        $veteran_member_order = Db::name('order')
            ->where($order_where)
            ->where('member_id', 'in', $veteran_member)
            ->sum('pay_money');
        $data[] = ['value' => $new_member_order, 'name' => '新客户成交额'];
        $data[] = ['value' => $veteran_member_order, 'name' => '老客户成交额'];
        $count2 = Db::name('order')
            ->where($order_where)
            ->where('member_id', 'in', $new_member)->count();
        msg(0, '', $data, $count2);
    }

    //成交客户数据统计2
    public function dealRadio2()
    {
        $where[] = ['m.openid', '<>', ''];
        $where[] = ['o.status', 'in', [2, 3, 5, 6]];
        $where[] = ['o.is_del', '=', 0];

        $new_member_order = Db::name('order')->alias('o')
            ->join('member m', 'm.id=o.member_id')
            ->where($where)
            ->where('m.create_time', '>', time() - (7 * 86400))
            ->count();
        $veteran_member_order = Db::name('order')->alias('o')
            ->join('member m', 'm.id=o.member_id')
            ->where($where)
            ->where('m.create_time', '<', time() - (7 * 86400))
            ->count();
        $data[] = ['value' => $new_member_order, 'name' => '新成交客户'];
        $data[] = ['value' => $veteran_member_order, 'name' => '老成交客户'];
        msg(0, '', $data, $veteran_member_order);
    }

    public function test()
    {
        $day1 = '2024-12-11';
        $day2 = '2024-12-16';
        if ($day1 > $day2) {
            return $day1;
        } else {
            return $day2;
        }
    }

    //退款测试
    public function refund2()
    {
        $order_id = $this->request->param('id/d', 0);
        $order_info = Db::name('order')->where('id', $order_id)->find();
        $config = config('wechat.wxpay');
        $app = Factory::payment($config);
        $result = $app->refund->byOutTradeNumber($order_info['order_no'], $order_info['order_no'], $order_info['pay_money'] * 100, $order_info['pay_money'] * 100, [
            // 可在此处传入其他参数，详细参数见微信支付文档
            'refund_desc' => '订单退款',
        ]);
        msg(0, '', $result['result_code'], $result);
    }

    //省的数量
    public function businessProvince()
    {
        $data = $this->request->param();
        //获取中间坐标 获取当前省 市 区 坐标组的中心位置显示数量
        $data_list = getAddressByLocation($data['latitude'], $data['longitude']);
        $data_list = json_decode($data_list, true);
        msg(0, '', $data_list);

//        {
//            id: 1,
//        latitude: 39.908517,
//        longitude: 116.397128,
//        name: '商家A',
//        iconPath: 'http://wxcc.jnsgs.cn/uploads/images/20240729/69dc963ad1b45ca870fed98104ffa614.png',
//        width: 50,
//        height: 50
//      },

    }

    //市里数量
    public function businessCity()
    {
        $data = $this->request->param();
        try {
            $data_list = getAddressByLocation($data['latitude'], $data['longitude']);
            $data_list = json_decode($data_list, true);

            $business_list = Db::name('business')->where([
                'province' => $data_list['data']['province'],
                'is_del' => 0,
                'status' => 1,
//                'operation_status' => 1
            ])->select();
            $groupedItems = [];
            foreach ($business_list as $item) {
                $goods_where = array(['status', '=', 1,], ['inventory', '>', 0], ['business_id', '=', $item['id']]);
                $goods = Db::name('goods')->where($goods_where)->select();
                if ($goods) {
                    $groupedItems[$item['city']][] = [$item['latitude'], $item['longitude']];
                }
            }
            $marks = [];
            $j = 0;
            foreach ($groupedItems as $k => $v) {
                $marks[$j]['id'] = $j;
                $marks[$j]['num'] = count($v);
                $marks[$j]['distance'] = GetCenterFromDegrees($v);
                ++$j;
            }
            msg(0, '', $marks);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //区数量列表
    public function businessAreaList()
    {
        $data = $this->request->param();
        try {
            $data_list = getAddressByLocation($data['latitude'], $data['longitude']);
            $data_list = json_decode($data_list, true);

            $business_list = Db::name('business')->where([
                'city' => $data_list['data']['city'],
                'is_del' => 0,
                'status' => 1,
//                'operation_status' => 1
            ])->select();
            $groupedItems = [];
            foreach ($business_list as $item) {
                $goods_where = array(['status', '=', 1,], ['inventory', '>', 0], ['business_id', '=', $item['id']]);
                //获取商品
                $goods = Db::name('goods')->where($goods_where)->select();
                if ($goods) {
                    $groupedItems[$item['area']][] = [$item['latitude'], $item['longitude']];
                }
            }
            $marks = [];
            $j = 0;
            foreach ($groupedItems as $k => $v) {
                $marks[$j]['id'] = $j;
                $marks[$j]['num'] = count($v);
                $marks[$j]['distance'] = GetCenterFromDegrees($v);
                ++$j;
            }
            msg(0, '', $marks);
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), '');
        }
    }

    //区域的商店列表数量
    public function businessListMap()
    {
        $data = $this->request->param();
        try {
            $data_list = getAddressByLocation($data['latitude'], $data['longitude']);
            $data_list = json_decode($data_list, true);
            msg(0, '', $data_list['data']['name']);
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取推荐关键词
    public function getRecommendList()
    {
        $data_list = Db::name('recommend')
            ->where([
                'status' => 1,
                'is_del' => 0
            ])
            ->order('sort desc')
            ->select();
        msg(0, '查询成功', $data_list);
    }

    //预售提醒定时任务 todo 需要去测试
    //sAY9t0W7vzqNKh6izxsDczskUN9I5eIHO6OLAL5VMSE
    public function repaySend()
    {
        $now_time = date('H:i', time());
        $goods_list = Db::name('goods')
            ->alias('g')
            ->join('business b', 'g.business_id=b.id')
            ->where([
                ['g.status', '=', 1],
                ['g.inventory', '>', 0],
                ['g.purchase_time_start', '<', $now_time],
                ['g.purchase_time_end', '>', $now_time],
                ['b.operation_status', '=', 1],
                ['b.status', '=', 1],
            ])->column('g.id');
        if (!$goods_list) {
            msg(0, '暂无内容', '');
        }

        $config = [
            'app_id' => config('wechat.appID'),
            'secret' => config('wechat.AppSecret'),
        ];
        $app = Factory::miniProgram($config);
        //todo 后期改为删除
        $presale_list = Db::name('presale')->where([
            ['is_del', '=', 0],
            ['goods_id', 'in', $goods_list]
        ])->select();
        foreach ($presale_list as $k2 => $v2) {
            $goods_info = Db::name('goods')->find($v2['goods_id']);
            //判断商家是否上线
            $business_info = Db::name('business')->find($goods_info['business_info']);
            if ($business_info['operation_status'] != 1) {
                continue;
            }
            $member_info = Db::name('member')->find($v2['member_id']);
            $send_data = [
                'template_id' => 'sAY9t0W7vzqNKh6izxsDczskUN9l5elHo6OLAL5VMSE', // 所需下发的订阅模板id
                'touser' => $member_info['openid'],     // 接收者（用户）的 openid
                'page' => 'pages/detailsPage/detailsPage?shopId=' . $goods_info['business_id'] . '&listId=' . $goods_info['id'] . '&identify=1',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
                'data' => [
                    'thing10' => [
                        'value' => $goods_info['name'],
                    ],
                    'date3' => [
                        'value' => $goods_info['purchase_time_start'],
                    ],
                    'date4' => [
                        'value' => $goods_info['purchase_time_end'],
                    ],
                ],
            ];
            $data = $app->subscribe_message->send($send_data);
            Db::name('presale')->update([
                'id' => $v2['id'],
                'is_del' => 1,
                'send_time' => time()
            ]);
        }
        msg(0, '发送完成', $data);
    }

    //定时任务 商家余额到账 todo 定时任务
    public function getAccount()
    {
        Db::startTrans();
        try {
            $limit = 20;
            $page = Cache::get('getAccount_page');
            if (!$page) {
                $page = 1;
                Cache::set('getAccount_page', $page);
            }
            $order_where = [
                ['status', 'in', [3, 6, 5]],//3待评价 4已退款 5已失效 6已核销
                ['is_to', '=', 0]
            ];
            $order_list = Db::name('order')
                ->page($page, $limit)
                ->where($order_where)
                ->select();

            if (!$order_list) {
                $page = 1;
                Cache::set('getAccount_page', $page);
                return;
            }
            Cache::set('getAccount_page', ++$page);
            foreach ($order_list as $k => $v) {
                //获取商家信息
                $business_info = Db::name('business')->find($v['business_id']);
                $now = time();
                $days = floor(abs($now - $v['write_time']) / (60 * 60 * 24));
                if ($days >= $business_info['to_day']) {
//                    if ($v['status'] == 4 && $v['is_houtui'] == 1) {
//                        daoZhang($v, '订单核销：' . $v['order_no']);
//                    }
                    if ($v['status'] == 3 || $v['status'] == 6) {
                        daoZhang($v, '订单核销：' . $v['order_no']);
                    }
                }
                //失效订单设置
                if ($v['status'] == 5) {
                    $days = floor(abs($now - $v['pay_time']) / (60 * 60 * 24));
                    if ($days >= $business_info['to_day']) {
                        daoZhang($v, '失效订单到账：' . $v['order_no']);
                    }
                }
            }
            Db::commit();
            msg(0, '查询成功', $order_list);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    public function edit_img()
    {
        try {
            $request = Request::instance();
            $domain = $request->domain();
            $string = $domain . '/uploads/20241119/ee12ca1e24bbc5009e4a08f14d31a315.jpg';
            //https://jxsg.lmweixin.com/uploads/20241119/ee12ca1e24bbc5009e4a08f14d31a315.jpg
            $a = edit_img($string);
            dump($a);
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //增加边框
    public function add_border()
    {
        $c = addBorder('http://jxsg.lmweixin.com/uploads/images/20241123/739729f3a7b347c0a754465c504c6e33.png');
        dump($c);
    }

    public function c2()
    {
        $request = Request::instance();
        $domain = $request->domain();
        $string = $domain . '/upload/ai/code/user/wx_tx/20241123/337f87d598d95308e342e698c3f54e58.png';
        dump($string);
        $c22 = c2($string);
        dump($c22);
    }

    public function getPhone2()
    {
        try {
            $data = $this->request->param();
            $config = config('wechat.config');
            $app = Factory::miniProgram($config);
            $data = $app->phone_number->getUserPhoneNumber($data['code']);
            msg(0, '查询成功', $data);
        } catch (\Exception $e) {
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }

    }

    //初始换数据
    public function delInit()
    {
        //
        $data = array(
            'business', 'business_finance', 'collect',
            'comment', 'comment_img', 'employ',
            'fraction_record', 'goods',
            'member', 'member_coupons',
            'member_experience', 'message',
            'message_switch', 'order',
            'platform_msg', 'presale',
            'question_feedback', 'question_feedback_img',
        );
        Db::startTrans();
        try {
            foreach ($data as $k => $v) {
                Db::name($v)->where('id', '<>', 0)->delete(true);
            }
            Db::commit();
            msg(0, '查询成功', $data);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }

    //设置图片水印
    public function setSY()
    {

        // 要处理的图片路径
        $imagePath = 'uploads/20241210/7ca923f0d4923d6e747c4c07d1601511.jpg';

// 实例化Image对象
        $image = Image::open($imagePath);

// 设置水印图片的路径
        $waterImagePath = 'uploads/images/20241210/2047a9dd42025defd04ab9b6f0b54176.png';

// 设置水印位置和透明度
        $image->water($waterImagePath, Image::WATER_NORTHWEST, 50); // 左上角, 透明度50%
        $image->water($waterImagePath, 2, 50); // 左上角, 透明度50%
        $image->water($waterImagePath, 3, 50); // 左上角, 透明度50%
        $image->water($waterImagePath, 4, 50); // 左上角, 透明度50%
        $image->water($waterImagePath, 5, 50); // 左上角, 透明度50%
        $image->water($waterImagePath, 6, 50); // 左上角, 透明度50%
        $image->water($waterImagePath, 7, 50); // 左上角, 透明度50%
        $image->water($waterImagePath, 8, 50); // 左上角, 透明度50%
        $image->water($waterImagePath, 9, 50); // 左上角, 透明度50%
// 保存处理后的图片
        $data = $image->save($imagePath); // 如果想保存为新图片可以提供新的路径
        msg(0, '11', $data);
    }

    //添加文字水印
    public function setSYText()
    {
// 要处理的图片路径
        $imagePath = 'uploads/20241210/c3b622d7083e673ebb99e5a01dc2f20b.jpg';

// 实例化图像处理对象
        $image = Image::open($imagePath);

// 添加文字水印
        $text = 'Your Watermark Text'; // 水印文字
        $fontPath = 'path/to/your/font.ttf'; // 字体文件路径，确保服务器上有该字体
        $fontPath='font/test.ttf';
        $fontSize = 20; // 字体大小
        $color = '#ffffff'; // 水印颜色

// 添加水印，参数依次是水印文字，字体文件，字体大小，颜色以及水印位置
        $image->text($text, $fontPath, $fontSize, $color, 1,0,-45);
        $image->text($text, $fontPath, $fontSize, $color, 2,0,-45);
        $image->text($text, $fontPath, $fontSize, $color, 3,0,-45);
        $image->text($text, $fontPath, $fontSize, $color, 4,0,-45);
        $image->text($text, $fontPath, $fontSize, $color, 5,0,-45);
        $image->text($text, $fontPath, $fontSize, $color, 6,0,-45);
        $image->text($text, $fontPath, $fontSize, $color, 7,0,-45);
        $image->text($text, $fontPath, $fontSize, $color, 8,0,-45);
        $image->text($text, $fontPath, $fontSize, $color, 9,0,-45);

// 保存处理后的图片
        $savePath = 'uploads/20241210/7ca923f0d4923d6e747c4c07d16015111.jpg';
        $image->save($savePath);
    }

    //大屏接口
    public function cIndex(){
        $a=Db::name('business')
            ->where(['is_del'=>0,'status'=>0])
            ->count();
        //待审核商家
        $b=Db::name('goods')
            ->where(['is_del'=>0,'status'=>2])
            ->count();
        $c=Db::name('question_feedback')
            ->where(['is_del'=>0,'is_reply'=>0])
            ->count();

        $d=Db::name('business_finance')
            ->where(['type'=>2,'status'=>0])
            ->count();
        $data['a']=$a;
        $data['b']=$b;
        $data['c']=$c;
        $data['d']=$d;
        msg(0,'查询更改',$data);
    }

    public function cIndex2(){
        //营业中商家数量 商品总数  上架商品总数
        $a=Db::name('business')
            ->where(['is_del'=>0,'status'=>1,'operation_status'=>1])
            ->count();

        //商品总数

        $b=Db::name('goods')
            ->where('is_del','=',0)
            ->where('status','in',[1,4])
            ->count();

        $c=Db::name('goods')
            ->where('is_del','=',0)
            ->where('status','=',1)
            ->count();

        //未核销订单总数
        $d=Db::name('order')
            ->where(['is_del'=>0,'status'=>2])
            ->count();

        //已失效订单总数
        $e=Db::name('order')
            ->where(['is_del'=>0,'status'=>5])
            ->count();


        $data['a']=$a;
        $data['b']=$b;
        $data['c']=$c;
        $data['d']=$d;
        $data['e']=$e;
        msg(0,'查询更改',$data);
    }

    //位置定时
    public function getAddress()
    {
        Db::startTrans();
        try {
            $limit = 20;
            $page = Cache::get('getAddress_page');
            if (!$page) {
                $page = 1;
                Cache::set('getAddress_page', $page);
            }
            $order_where = [
                ['is_c', '=', 1],
                ['is_del', '=', 0]
            ];
            $order_list = Db::name('cmap')
                ->page($page, $limit)
                ->where($order_where)
                ->order('create_time desc')
                ->select();

            if (!$order_list) {
                $page = 1;
                Cache::set('getAddress_page', $page);
                return;
            }
            Cache::set('getAddress_page', ++$page);
            foreach ($order_list as $k => $v) {
                $address = getLWByAddress($v['province'] . $v['city'] . $v['area'] . $v['address']);
                $address = json_decode($address, true);
                $update_data=array();
                if ($address['code'] == 0) {
                    $update_data['id']=$v['id'];
                    $update_data['longitude'] = $address['data'][0];
                    $update_data['latitude'] = $address['data'][1];
                    $update_data['is_c'] = 2;
                }
                Db::name('cmap')->update($update_data);
            }
            Db::commit();
            msg(0, '查询成功', $order_list);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), date('Y-m-d H:i:s'));
        }
    }


}